package com.intelligent.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intelligent.entity.PurchaseOrder;
import com.intelligent.entity.PurchaseSupplier;
import com.intelligent.entity.PurchaseDemand;
import com.intelligent.entity.PurchaseStorage;
import com.intelligent.mapper.PurchaseOrderMapper;
import com.intelligent.mapper.PurchaseSupplierMapper;
import com.intelligent.mapper.PurchaseDemandMapper;
import com.intelligent.mapper.PurchaseStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购工作台服务类
 * 提供采购工作台所需的各种数据统计和查询服务
 */
@Service
public class ProcurementWorkbenchService {

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    
    @Autowired
    private PurchaseSupplierMapper purchaseSupplierMapper;
    
    @Autowired
    private PurchaseDemandMapper purchaseDemandMapper;
    
    @Autowired
    private PurchaseStorageMapper purchaseStorageMapper;

    /**
     * 获取采购工作台统计数据
     * 包括采购完成率、订单数、采购金额、供应商数量、库存价值、质检合格率
     */
    public Map<String, Object> getProcurementStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取本月时间范围
        LocalDate now = LocalDate.now();
        LocalDate monthStart = now.withDayOfMonth(1);
        Date startDate = Date.from(monthStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
        
        // 本月采购完成率
        QueryWrapper<PurchaseOrder> completedWrapper = new QueryWrapper<>();
        completedWrapper.eq("storage_status", 2) // 全部入库
                .ge("expected_storage_time", startDate)
                .le("expected_storage_time", endDate);
        long completedOrders = purchaseOrderMapper.selectCount(completedWrapper);
        
        QueryWrapper<PurchaseOrder> totalWrapper = new QueryWrapper<>();
        totalWrapper.ge("expected_storage_time", startDate)
                .le("expected_storage_time", endDate);
        long totalOrders = purchaseOrderMapper.selectCount(totalWrapper);
        
        double completionRate = totalOrders > 0 ? (double) completedOrders / totalOrders * 100 : 0;
        statistics.put("completionRate", Math.round(completionRate * 100.0) / 100.0);
        
        // 订单数
        statistics.put("orderCount", totalOrders);
        
        // 采购金额
        List<PurchaseOrder> monthOrders = purchaseOrderMapper.selectList(totalWrapper);
        BigDecimal totalAmount = monthOrders.stream()
                .map(PurchaseOrder::getPurchaseAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        statistics.put("purchaseAmount", totalAmount);
        
        // 供应商数量
        QueryWrapper<PurchaseSupplier> supplierWrapper = new QueryWrapper<>();
        supplierWrapper.eq("status", 1); // 正常状态
        long supplierCount = purchaseSupplierMapper.selectCount(supplierWrapper);
        statistics.put("supplierCount", supplierCount);
        
        // 库存价值（基于已入库的采购金额计算）
        QueryWrapper<PurchaseStorage> storageWrapper = new QueryWrapper<>();
        storageWrapper.eq("storage_status", 2); // 已入库
        List<PurchaseStorage> storageList = purchaseStorageMapper.selectList(storageWrapper);
        BigDecimal inventoryValue = storageList.stream()
                .map(PurchaseStorage::getTotalAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        statistics.put("inventoryValue", inventoryValue);
        
        // 质检合格率
        long totalQcCount = storageList.size();
        long passedQcCount = storageList.stream()
                .filter(storage -> storage.getQcStatus() != null && storage.getQcStatus() == 1)
                .count();
        double qualityRate = totalQcCount > 0 ? (double) passedQcCount / totalQcCount * 100 : 0;
        statistics.put("qualityRate", Math.round(qualityRate * 100.0) / 100.0);
        
        return statistics;
    }

    /**
     * 获取采购待办事项
     * 包括待审核采购申请、待确认订单、逾期订单、质检异常等
     */
    public Map<String, Object> getProcurementTodos() {
        Map<String, Object> todos = new HashMap<>();
        
        // 待审核采购申请（采购需求中待采购的）
        QueryWrapper<PurchaseDemand> demandWrapper = new QueryWrapper<>();
        demandWrapper.eq("purchase_status", 0); // 待采购入库
        long pendingDemands = purchaseDemandMapper.selectCount(demandWrapper);
        todos.put("pendingApprovals", pendingDemands);
        
        // 待确认采购订单（待入库状态）
        QueryWrapper<PurchaseOrder> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("storage_status", 0); // 待入库
        long pendingOrders = purchaseOrderMapper.selectCount(pendingWrapper);
        todos.put("pendingConfirmations", pendingOrders);
        
        // 已逾期采购订单（期望入库时间已过但未全部入库）
        QueryWrapper<PurchaseOrder> overdueWrapper = new QueryWrapper<>();
        overdueWrapper.lt("expected_storage_time", new Date())
                .in("storage_status", Arrays.asList(0, 1)); // 待入库或部分入库
        long overdueOrders = purchaseOrderMapper.selectCount(overdueWrapper);
        todos.put("overdueOrders", overdueOrders);
        
        // 入库质检异常（质检不合格的）
        QueryWrapper<PurchaseStorage> qcWrapper = new QueryWrapper<>();
        qcWrapper.eq("qc_status", 0) // 待质检
                .or()
                .isNotNull("unqualified_quantity")
                .gt("unqualified_quantity", 0); // 有不合格数量
        long qcAbnormal = purchaseStorageMapper.selectCount(qcWrapper);
        todos.put("qcAbnormal", qcAbnormal);
        
        return todos;
    }

    /**
     * 获取采购趋势数据
     * 包括年度目标、本月目标、采购趋势等
     */
    public Map<String, Object> getProcurementTrends() {
        Map<String, Object> trends = new HashMap<>();
        
        // 年度目标（假设年度目标为1000万）
        BigDecimal yearTarget = new BigDecimal("10000000");
        
        // 年度已完成金额
        LocalDate yearStart = LocalDate.now().withDayOfYear(1);
        Date yearStartDate = Date.from(yearStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
        
        QueryWrapper<PurchaseOrder> yearWrapper = new QueryWrapper<>();
        yearWrapper.ge("expected_storage_time", yearStartDate);
        List<PurchaseOrder> yearOrders = purchaseOrderMapper.selectList(yearWrapper);
        BigDecimal yearCompleted = yearOrders.stream()
                .map(PurchaseOrder::getPurchaseAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        Map<String, Object> yearTrend = new HashMap<>();
        yearTrend.put("current", yearCompleted);
        yearTrend.put("target", yearTarget);
        yearTrend.put("percentage", yearTarget.compareTo(BigDecimal.ZERO) > 0 ? 
                yearCompleted.divide(yearTarget, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).doubleValue() : 0);
        trends.put("yearTarget", yearTrend);
        
        // 本月目标（假设本月目标为100万）
        BigDecimal monthTarget = new BigDecimal("1000000");
        
        // 本月已完成金额
        LocalDate monthStart = LocalDate.now().withDayOfMonth(1);
        Date monthStartDate = Date.from(monthStart.atStartOfDay(ZoneId.systemDefault()).toInstant());
        
        QueryWrapper<PurchaseOrder> monthWrapper = new QueryWrapper<>();
        monthWrapper.ge("expected_storage_time", monthStartDate);
        List<PurchaseOrder> monthOrders = purchaseOrderMapper.selectList(monthWrapper);
        BigDecimal monthCompleted = monthOrders.stream()
                .map(PurchaseOrder::getPurchaseAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        Map<String, Object> monthTrend = new HashMap<>();
        monthTrend.put("current", monthCompleted);
        monthTrend.put("target", monthTarget);
        monthTrend.put("percentage", monthTarget.compareTo(BigDecimal.ZERO) > 0 ? 
                monthCompleted.divide(monthTarget, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).doubleValue() : 0);
        trends.put("monthTarget", monthTrend);
        
        // 采购趋势（最近12个月的采购金额趋势）
        List<Map<String, Object>> trendData = new ArrayList<>();
        for (int i = 11; i >= 0; i--) {
            LocalDate trendMonth = LocalDate.now().minusMonths(i);
            LocalDate trendStart = trendMonth.withDayOfMonth(1);
            LocalDate trendEnd = trendMonth.withDayOfMonth(trendMonth.lengthOfMonth());
            
            QueryWrapper<PurchaseOrder> trendWrapper = new QueryWrapper<>();
            trendWrapper.ge("expected_storage_time", Date.from(trendStart.atStartOfDay(ZoneId.systemDefault()).toInstant()))
                    .le("expected_storage_time", Date.from(trendEnd.atStartOfDay(ZoneId.systemDefault()).toInstant()));
            
            List<PurchaseOrder> trendOrders = purchaseOrderMapper.selectList(trendWrapper);
            BigDecimal trendAmount = trendOrders.stream()
                    .map(PurchaseOrder::getPurchaseAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", trendMonth.getMonthValue() + "月");
            monthData.put("amount", trendAmount);
            trendData.add(monthData);
        }
        trends.put("procurementTrend", trendData);
        
        return trends;
    }

    /**
     * 获取采购订单列表
     */
    public Map<String, Object> getProcurementOrders(int page, int pageSize, String keyword, String status, String expectedDate) {
        QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
        
        // 关键词搜索（订单号或供应商）
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like("order_no", keyword)
                    .or().like("supplier_id", keyword));
        }
        
        // 订单状态筛选
        if (StringUtils.hasText(status)) {
            wrapper.eq("storage_status", status);
        }
        
        // 期望到货时间筛选
        if (StringUtils.hasText(expectedDate)) {
            wrapper.like("expected_storage_time", expectedDate);
        }
        
        // 分页查询
        Page<PurchaseOrder> pageObj = new Page<>(page, pageSize);
        IPage<PurchaseOrder> result = purchaseOrderMapper.selectPage(pageObj, wrapper);
        
        // 构建返回结果
        Map<String, Object> response = new HashMap<>();
        
        // 转换订单数据，添加供应商名称
        List<Map<String, Object>> orderList = result.getRecords().stream().map(order -> {
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("id", order.getId());
            orderMap.put("orderNo", order.getOrderNo());
            orderMap.put("purchaseType", getPurchaseTypeText(order.getPurchaseType()));
            orderMap.put("expectedStorageTime", order.getExpectedStorageTime());
            orderMap.put("supplierId", order.getSupplierId());
            orderMap.put("supplierName", getSupplierName(order.getSupplierId()));
            orderMap.put("purchaseQuantity", order.getPurchaseQuantity());
            orderMap.put("purchaseAmount", order.getPurchaseAmount());
            orderMap.put("storageStatus", order.getStorageStatus());
            orderMap.put("intoStorage", order.getIntoStorage());
            orderMap.put("quantityPurchased", order.getQuantityPurchased());
            orderMap.put("returnedQuantity", order.getReturnedQuantity());
            orderMap.put("paymentStatus", order.getPaymentStatus());
            orderMap.put("amountPaid", order.getAmountPaid());
            orderMap.put("amountDue", order.getAmountDue());
            return orderMap;
        }).collect(Collectors.toList());
        
        response.put("records", orderList);
        response.put("total", result.getTotal());
        response.put("pages", result.getPages());
        response.put("current", result.getCurrent());
        response.put("size", result.getSize());
        
        return response;
    }

    /**
     * 获取供应商列表
     */
    public Map<String, Object> getSuppliers() {
        QueryWrapper<PurchaseSupplier> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1); // 正常状态
        
        List<PurchaseSupplier> suppliers = purchaseSupplierMapper.selectList(wrapper);
        
        Map<String, Object> response = new HashMap<>();
        response.put("suppliers", suppliers);
        response.put("total", suppliers.size());
        
        return response;
    }

    /**
     * 获取采购订单详情
     */
    public Map<String, Object> getProcurementOrderDetail(Long orderId) {
        PurchaseOrder order = purchaseOrderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        Map<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("id", order.getId());
        orderDetail.put("orderNo", order.getOrderNo());
        orderDetail.put("purchaseType", getPurchaseTypeText(order.getPurchaseType()));
        orderDetail.put("expectedStorageTime", order.getExpectedStorageTime());
        orderDetail.put("supplierId", order.getSupplierId());
        orderDetail.put("supplierName", getSupplierName(order.getSupplierId()));
        orderDetail.put("purchaseQuantity", order.getPurchaseQuantity());
        orderDetail.put("purchaseAmount", order.getPurchaseAmount());
        orderDetail.put("storageStatus", order.getStorageStatus());
        orderDetail.put("storageStatusText", getStorageStatusText(order.getStorageStatus()));
        orderDetail.put("intoStorage", order.getIntoStorage());
        orderDetail.put("quantityPurchased", order.getQuantityPurchased());
        orderDetail.put("returnedQuantity", order.getReturnedQuantity());
        orderDetail.put("paymentStatus", order.getPaymentStatus());
        orderDetail.put("paymentStatusText", getPaymentStatusText(order.getPaymentStatus()));
        orderDetail.put("amountPaid", order.getAmountPaid());
        orderDetail.put("amountDue", order.getAmountDue());
        
        return orderDetail;
    }

    /**
     * 获取供应商名称
     */
    private String getSupplierName(Long supplierId) {
        if (supplierId == null) {
            return "未知供应商";
        }
        PurchaseSupplier supplier = purchaseSupplierMapper.selectById(supplierId);
        return supplier != null ? supplier.getSupplierName() : "未知供应商";
    }

    /**
     * 获取采购类型文本
     */
    private String getPurchaseTypeText(Integer purchaseType) {
        if (purchaseType == null) {
            return "未知类型";
        }
        switch (purchaseType) {
            case 0: return "生产采购";
            case 1: return "备货采购";
            default: return "其他采购";
        }
    }

    /**
     * 获取入库状态文本
     */
    private String getStorageStatusText(Integer storageStatus) {
        if (storageStatus == null) {
            return "未知状态";
        }
        switch (storageStatus) {
            case 0: return "待入库";
            case 1: return "部分入库";
            case 2: return "全部入库";
            default: return "未知状态";
        }
    }

    /**
     * 获取付款状态文本
     */
    private String getPaymentStatusText(Integer paymentStatus) {
        if (paymentStatus == null) {
            return "未知状态";
        }
        switch (paymentStatus) {
            case 0: return "待付款";
            case 1: return "部分付款";
            case 2: return "已付款";
            case 3: return "退货";
            default: return "未知状态";
        }
    }
}